<template>
  <div class="home">
    <h2>商品列表</h2>
    <ul style="list-style-type: none;">
      <li v-for="product in products" :key="product.id">
        {{ product.name }} - ${{ product.price }}
        <button @click="addToCart(product.id)">添加至购物车</button>
      </li>
    </ul>

    <h2>购物车</h2>
    <ul v-if="cart.length" style="list-style-type: none;">
      <li v-for="item in cart" :key="item.id" class="cart-item">
        {{ item.name }} - ${{ item.price }} x {{ item.quantity }}
        <button @click="decreaseQuantity(item.id)" class="decrease-btn">减少</button>
        <button @click="removeFromCart(item.id)" class="remove-btn">移除</button>
      </li>
    </ul>
    <p v-else>未购买</p>

    <h3>总计: ${{ cartTotal }}</h3>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'

export default {
  name: 'HomeView',
  computed: {
    ...mapState(['products', 'cart']),
    ...mapGetters(['cartTotal'])
  },
  methods: {
    ...mapActions(['addToCart', 'removeFromCart', 'decreaseQuantity'])
  }
}
</script>
